<?php
class LanguagesController extends AppController {

	var $name = 'Languages';
	var $helpers = array('Linker','Avatar');
	var $uses = array('Language','UserLanguage','User','Word','Job', 'Event');

	function index() {
		$this->set('languages', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid language', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->Language->recursive=-1;
		$users = $this->User->find('all',array(
		    'joins'=>array(
		        array(
		        'table'=>'user_languages',
		        'alias'=>'UserLanguage', 
		        'conditions'=>array('User.id = UserLanguage.user_id')
		            )
		        ),
		    'conditions'=>array('UserLanguage.language_id'=>$id),'limit'=>20,
			'order'=>'UserLanguage.id DESC')
			);
		    
		$this->set('words',$this->Word->find('all',array('conditions'=>array('Word.language_id'=>$id),'limit'=>20)));
		$jobs = $this->Job->find('all',array('conditions'=>array('Job.language_id'=>$id),'order'=>'Job.id desc','limit'=>5));
		$this->set('users', $users);
		$this->set('jobs', $jobs);
		$this->set('language', $this->Language->findById($id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Language->create();
			if ($this->Language->save($this->data)) {
				$this->Session->setFlash(__('The language has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The language could not be saved. Please, try again.', true));
			}
		}
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid language', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Language->save($this->data)) {
				$this->Session->setFlash(__('The language has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The language could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Language->read(null, $id);
		}
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for language', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Language->delete($id)) {
			$this->Session->setFlash(__('Language deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Language was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
?>